from django.shortcuts import render
from django.views.decorators.http import require_http_methods


import os

from django.conf import settings
from django.views.decorators.csrf import csrf_exempt


ROOT_PATH = getattr(settings, 'FILES_ROOT', os.path.join(settings.BASE_DIR, 'user_files'))


@csrf_exempt
@require_http_methods(['GET'])
def list(request, path=""):
    full_path = os.path.join(settings.BASE_DIR, path.strip('/'))
    print(full_path)
    if not os.path.exists(full_path):
        return render(request, "404.html", status=404)
    breadcrumbs = path.strip("/").split("/") if path else []
    items = []
    for name in sorted(os.listdir(full_path)):
        item_path = path + "/" + name
        absolute_item_path = os.path.join(full_path, name)
        is_dir = os.path.isdir(absolute_item_path)
        if is_dir:
            icon = "folder"
        else:
            ext = os.path.splitext(name)[1].lower()
            if ext == ".pdf":
                icon = "filetype-pdf"
            elif ext == ".docx":
                icon = "filetype-docx"
            elif ext == ".doc":
                icon = "filetype-doc"
            elif ext == ".md":
                icon = "filetype-md"
            else:
                icon = "file-earmark"
        print(item_path)
        items.append({
            'name': name,
            'path': item_path,
            'is_dir': is_dir,
            'icon': icon
        })
        # 如果 items 为空，则不传 items 给模板
    if_show_items = len(items) > 0
    return render(request, "file/list.html", {
        "if_show_items": if_show_items,
        "items": items,
        "current_path": path,
        "breadcrumbs": breadcrumbs,
    })
